// console.log('Hello from the content-script')
const url = document.URL.split('?')[0]
if (url.endsWith('/details.php')) {
    // console.log('详情页')
    defaultDetailsDetect()
} else if (url.endsWith('/torrents.php')) {
    // console.log('列表页面')
    // defaultTorrentsDetect()
} else {
    // console.log('torrent-manager-extension: 暂未支持的页面')
}

// 详情页通用查找
function defaultDetailsDetect() {
    let title = '???'
    let title0 = ''
    let category = ''
    const outerDom = document.getElementById('outer')
    if (outerDom) {
    const tableDom = outerDom.getElementsByTagName('table')[0]
    const cells = tableDom.getElementsByClassName('rowfollow')
    title = cells[1].innerHTML // 优先副标题
    title0 = document.getElementById('top').innerText
    if (!title) { // 种子名称
        //   title = cells[0].getElementsByTagName('a')[0].innerHTML
        title = document.getElementById('top').innerText
    }
    const info = cells[2].innerText
    category = matchCategory(info)
    }
    const links = document.links
    const torrentLinks = []
    for (let index = 0; index < links.length; index++) {
        const link = links[index];
        if (link.href.indexOf('/download.php?') >= 0) {
            if (link.href.indexOf('passkey') >= 0 || link.href.indexOf('downhash') >= 0) {
                // console.log(link.innerHTML)
                torrentLinks.push({ address: link.href, title: link.innerText })
            }
        }
    }

    if (torrentLinks.length > 0) {
        chrome.runtime.sendMessage({ type: 'TORRENT-INFO', title: title, title0: title0, category: category, torrentLinks: torrentLinks }, response => {
        // console.log('content get response:', response);
        });
    }
}

// 列表页通用查找
function defaultTorrentsDetect() {
    const tableDom = document.getElementsByClassName('torrents')
    // console.log(tableDom)
    if (tableDom[0]) {
        const rowDoms = tableDom[0].firstElementChild.childNodes
        // console.log(rowDoms)
        rowDoms.forEach(rowDom => {
            if (rowDom.tagName === 'TR') {
                if (rowDom.firstElementChild.className !== 'colhead') {
                    // console.log(rowDom);
                    let title = '???'
                    let category = ''
                    const torrentLinks = []
                    // 解析
                    const colDoms = []
                    rowDom.childNodes.forEach(n => {
                        if (n.tagName === 'TD') colDoms.push(n)
                    })
                    // console.log(colDoms);
                    // 分类
                    category = matchCategory(colDoms[0].firstElementChild.firstElementChild.title)
                    // console.log(category);
                    // 标题
                    const torrentDom = colDoms[1].firstElementChild.firstElementChild.firstElementChild.querySelectorAll('td.embedded')[0]
                    const titleDom1 = torrentDom.getElementsByTagName('a')[0]
                    const titleDom2 = torrentDom.lastChild
                    title = titleDom2.nodeName === '#text' ? titleDom2.textContent : titleDom2.innerText
                    if (!title) title = titleDom1.innerText
                    // console.log(title);
                    // 链接
                    torrentLinks.push({ address: titleDom1.href, title: titleDom1.innerText })
                    // console.log(torrentLinks);
                }
            }
        })
        // const rowsDom = tableDom.getElementsByTagName('tr')
        // console.log(rowsDom)
    }
}

function matchCategory(val) {
    // 0: {id: 1, name: "电影", folder: "Movies", description: null}
    // 1: {id: 2, name: "连续剧", folder: "TV-Series", description: ""}
    // 2: {id: 3, name: "动漫", folder: "Animation", description: null}
    // 3: {id: 4, name: "记录片", folder: "Documentary", description: null}
    // 4: {id: 5, name: "综艺", folder: "TV-Show", description: null}
    // 5: {id: 6, name: "软件", folder: "Software", description: null}
    // 6: {id: 7, name: "资料", folder: "Education", description: null}
    // 7: {id: 8, name: "游戏", folder: "Game", description: null}
    // 8: {id: 9, name: "音乐", folder: "Music", description: null}
    // 9: {id: 10, name: "体育", folder: "Sports", description: null}
    // 10: {id: 11, name: "其它", folder: "Other", description: null}
    // 11: {id: 12, name: "18+", folder: "Sex", description: null}

    // btschool, hddolby, m-team
    if (arrayIndexOf(['连续剧/TV-Series', 'TV Series电视剧', 'TV Series(影劇/綜藝)'], val)) {
        return 'TV-Series'
    } else if (arrayIndexOf(['电影/Movies', 'Movies电影', 'Movie(電影)'], val)) {
        return 'Movies'
    } else if (arrayIndexOf(['动漫/Animation', 'Animations动漫', 'Anime(動畫)'], val)) {
        return 'Animation'
    } else if (arrayIndexOf(['纪录片/Documentary', 'Documentaries纪录片', '紀錄教育'], val)) {
        return 'Documentary'
    } else if (arrayIndexOf(['综艺/TV-Show', 'TV Shows综艺', 'TV Series(影劇/綜藝)'], val)) {
        return 'TV-Show'
    } else if (arrayIndexOf(['软件/Software', '-', 'Software(軟體)'], val)) {
        return 'Software'
    } else if (arrayIndexOf(['资料/Education', 'Study学习', 'eBook(電子書)'], val)) {
        return 'Education'
    } else if (arrayIndexOf(['游戏/Game', 'Games游戏', 'PCGame(PC遊戲)'], val)) {
        return 'Game'
    } else if (arrayIndexOf(['音乐/Music', 'HQ Audio音乐', 'Music(AAC/ALAC)'], val)) {
        return 'Music'
    } else if (arrayIndexOf(['体育/Sports', 'Sports体育', 'Sports(運動)'], val)) {
        return 'Sports'
    } else if (arrayIndexOf(['-', '-', 'AV'], val)) { // m-team中分类数据行不同，未解析
        return 'Sex'
    } else {
        return 'Other'
    }
}
function arrayIndexOf(array, val) {
    for (let index = 0; index < array.length; index++) {
        if (val.indexOf(array[index]) >= 0) {
            return true
        }
    }
    return false
}
